package com.dwxt.cdms.admin.service;

import com.dwxt.cdms.base.Page;
import com.dwxt.cdms.dao.AdminHistoryMapper;
import com.dwxt.cdms.dao.AdminUserMapper;
import com.dwxt.cdms.entity.AdminHistory;
import com.dwxt.cdms.entity.AdminHistoryExample;
import com.dwxt.cdms.entity.AdminUser;
import com.dwxt.common.base.BaseResult;
import com.dwxt.common.util.DateUtils;
import com.dwxt.common.util.PartyUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class HistoryServiceAdmin {

    @Autowired
    private AdminHistoryMapper adminHistoryMapper;

    @Autowired
    private AdminUserMapper adminUserMapper;

    public void generate(String operate, String category) {
        try {
            AdminUser adminUser = adminUserMapper.selectByPrimaryKey(Integer.parseInt(PartyUtil.getCurrentUserId()));
            AdminHistory history = new AdminHistory();
            history.setUserId(adminUser.getId());
            history.setOperate(operate);
            history.setCategory(category);
            history.setUsername(adminUser.getPhone());
            adminHistoryMapper.insertSelective(history);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void generateLog(String phone,String operate, String category) {
        try {
            AdminHistory history = new AdminHistory();
            history.setUserId(0);
            history.setOperate(operate);
            history.setCategory(category);
            history.setUsername(phone);
            adminHistoryMapper.insertSelective(history);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public BaseResult selectPage(Page page, String startTime, String endTime, String category, String username) {
        PageHelper.startPage(page.getPageNum(), page.getPageSize());
        AdminHistoryExample example = new AdminHistoryExample();
        example.setOrderByClause("create_time desc");
        AdminHistoryExample.Criteria criteria = example.createCriteria();
        if (StringUtils.isNotBlank(startTime)) {
            criteria.andCreateTimeBetween(DateUtils.formatTime(startTime), DateUtils.formatTime(endTime));
        }
        if (StringUtils.isNotBlank(category)) {
            criteria.andCategoryEqualTo(category);
        }
        if (StringUtils.isNotBlank(username)) {
            criteria.andUsernameLike("%" + username + "%");
        }
        List<AdminHistory> adminHistories = adminHistoryMapper.selectByExample(example);
        PageInfo<AdminHistory> pageInfo = new PageInfo<>(adminHistories);
        return BaseResult.ok(pageInfo);
    }
}
